package com.lrkj.back.controller;

import java.io.ByteArrayOutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.ExcelUtils;
import com.lrkj.back.Const;
import com.lrkj.back.StartUpOnLoadData;
import com.lrkj.back.entity.*;
import com.lrkj.back.service.*;
import com.lrkj.back.vo.CharUtil;
import com.lrkj.back.vo.constant.PathInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.cbons.mamisay.parent.exception.BusinessException;

import com.github.pagehelper.PageInfo;


@Controller
@RequestMapping("/recover")
public class ZsHuiShouController extends BaseController{
	
	@Autowired
	private ZsHuishouService zsHuishou;
	@Autowired
	private ZsHuishouMingxiService zsHuishouMingxi;
	
	@Autowired
	private ZsWanglanpackageService zsWlPKService;
	
	@Autowired
	private ZsPackageImformationService zsPKIMService;
	
	@Autowired
	private ZsHuishouWutiaomaService tbWutiaoma;
	
	@Autowired
	private ZsWanglanService zsWlService;

	@Autowired
	private TbDepartmentService tbDepartmentService;

	@Autowired
	private TbEmployeeService tbEmployeeService;

	@Autowired
	private SendImservice sendImservice;




	
	@RequestMapping("/recoverList.do")
	public ModelAndView packageingList()throws BusinessException{
		return new ModelAndView("/huishou/huishou_list");
	}

	@RequestMapping("/recoverList")
	@ResponseBody
	public Map<String,Object> recoverList(@RequestParam Integer pageNo, @RequestParam Integer pageSize,String type, String depId, String searchTxt, String time,Integer timeType,String timeOrder,String sendId,HttpServletRequest request
										  ) throws BusinessException, ParseException {
		Map<String,Object> rtpMap = new HashMap<>();
		Map<String,Object> map =new HashMap<>();
		Date startTime = new Date();
		Date endTime = new Date();
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
		map.put("pageNo",pageNo);
		map.put("pageSize",pageSize);

		if(StringUtils.isNoneBlank(depId)&&Integer.valueOf(depId)!=0){
			map.put("depId",depId);
		}
		if(StringUtils.isNotBlank(searchTxt)){
			map.put("searchTxt", searchTxt);
		}
		if(StringUtils.isNotBlank(searchTxt)&&CharUtil.isChinese(searchTxt)){
			List<TbEmployee> tbEmployees = tbEmployeeService.findEmployee(map);
			List<String> empList = new ArrayList<>();
			for(TbEmployee tbEmployee:tbEmployees){
				empList.add(tbEmployee.getEmployeeNo());
			}
			if(!empList.isEmpty()){
				map.put("empNo",empList.toArray());
			}
		}
		try {
			if (StringUtils.isNotBlank(time)) {
				String [] times = time.split("一");
				if(times.length==2){
						StringBuffer stringBuffer = new StringBuffer(times[0]);
						StringBuffer stringBuffer2 = new StringBuffer(times[1]);
						times[0] = String.valueOf(stringBuffer.insert(times[0].indexOf("/")+1,"0"));
						times[1] = String.valueOf(stringBuffer2.insert(times[1].indexOf("/")+1,"0"));
						startTime = sdf2.parse(times[0]);
						endTime = sdf2.parse(times[1]);
						long timeNum  = endTime.getTime()+24l*60*60*1000;
						endTime.setTime(timeNum);
						if(timeType!=null){
							if(timeType==0){
							}else if(timeType ==1){
								long time1 = endTime.getTime()-12l*60*60*1000;
								endTime.setTime(time1);
							}else if(timeType ==2){
								long time2 = startTime.getTime()+12l*60*60*1000;
								startTime.setTime(time2);
							}
						}
						map.put("startTime",startTime);
						map.put("endTime",endTime);
				}
			}else{

				startTime = getTimesmorning();
				endTime = getTimesnight();
				if(timeType!=null){
					if(timeType==0){

					}else if(timeType ==1){
						long time1 = endTime.getTime()-12l*60*60*1000;
						endTime.setTime(time1);
					}else if(timeType ==2){
						long time2 = startTime.getTime()+12l*60*60*1000;
						startTime.setTime(time2);
					}
				}
				map.put("startTime",startTime);
				map.put("endTime",endTime);

			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		type = type==null?"0":type;
		int a ;
		int b;
		Integer totle = Integer.valueOf(type);

		if(StringUtils.isBlank(timeOrder)){
			timeOrder = "3";
		}
		map.put("timeOrder",timeOrder);

		if(StringUtils.isNotBlank(sendId)){
			Integer integer = Integer.valueOf(sendId);
			map.put("sendId",integer);
			List<TbDepartment> list = tbDepartmentService.findDepartment(map);
			List<String> depList = new ArrayList<>();
			if(list!=null&&list.size()!=0){

				for(TbDepartment tbDepartment :list){
					String depid = tbDepartment.getDepartmentId();
					depList.add(depid);
				}
				map.put("depList",depList);
			}else if(list.size()==0){
				depList.add("1");
				map.put("depList",depList);
			}
		}

		List<ZsHuishouMingxi> zsHuishouMingxiList = zsHuishouMingxi.findAllHuishouMingxi(map);

		Map<String,Map<Integer,List<String>>> tiaomaMap= new HashMap<>();
		for (int i = 0; i < zsHuishouMingxiList.size(); i++) {
			ZsHuishouMingxi zsHuishouMingxi = zsHuishouMingxiList.get(i);
			String keshi = zsHuishouMingxi.getHuishouKeshi();
			Integer packageId = zsHuishouMingxi.getHuishouWupinbaoMuban();
			String packageTiaoma = zsHuishouMingxi.getHuishouWupinbaoTiaoma();
			if(tiaomaMap.containsKey(keshi)){
				Map<Integer,List<String>> map1 = tiaomaMap.get(keshi);
				if(map1.containsKey(packageId)){
					List<String> list = map1.get(packageId);
					list.add(packageTiaoma);
					map1.put(packageId,list);
					tiaomaMap.put(keshi,map1);
				}else{
					List<String> list = new ArrayList<>();
					list.add(packageTiaoma);
					map1.put(packageId,list);
					tiaomaMap.put(keshi,map1);
				}
			}else{
				Map<Integer,List<String>> map1 = new HashMap<>();
				List<String> list = new ArrayList<>();
				list.add(packageTiaoma);
				map1.put(packageId,list);
				tiaomaMap.put(keshi,map1);
			}
		}
		PageInfo<ZsHuishouMingxi> page = zsHuishouMingxi.findAllHuishouMingxiPage(map,totle);

		List<ZsHuishouMingxi> zsHuishouMingxiList1 = page.getList();
		for (int i = 0; i < zsHuishouMingxiList1.size(); i++) {
			ZsHuishouMingxi zsHuishouMingxi  = zsHuishouMingxiList1.get(i);
			Integer packId = zsHuishouMingxi.getHuishouWupinbaoMuban();
			String keshi = zsHuishouMingxi.getHuishouKeshi();
			Map<Integer,List<String>> map1 = tiaomaMap.get(keshi);
			List<String> tiaomaList = map1.get(packId);
			String [] tiaomaArr = tiaomaList.toArray(new String [tiaomaList.size()]);
			zsHuishouMingxi.setTiaomaArr(tiaomaArr);
		}
		page.setList(zsHuishouMingxiList1);
		request.setAttribute("searchTxt", searchTxt==null?"":searchTxt);
		request.setAttribute("total", page.getPages());
		rtpMap.put("searchTxt", searchTxt==null?"":searchTxt);
		rtpMap.put("depMap",StartUpOnLoadData.depMap);
		rtpMap.put("empMap", StartUpOnLoadData.emMap);
		rtpMap.put("wlMap",StartUpOnLoadData.wanglanMap);
		rtpMap.put("data",page);
		return rtpMap;
	}

	//获得当天0点时间
	public static Date getTimesmorning(){
		Date date = new Date();
		date.setHours(0);
		date.setMinutes(0);
		date.setSeconds(0);
		return date;
	}
	//获得当天24点时间
	public static Date getTimesnight(){
		Date date = new Date();
		date.setHours(23);
		date.setMinutes(59);
		date.setSeconds(59);
		return date;
	}
	
	@RequestMapping("/recoverEdit.do")
	public ModelAndView packageingEdit(ZsHuishou zsHuishou, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{

//		ZsHuishou huishou = (huishouLiushui == null) ? new ZsHuishou() : zsHuishou.selectByPrimaryKey(huishouLiushui);
//		System.out.println(huishou);
//		request.setAttribute("huishou",huishou);
		return new ModelAndView("/huishou/huishou_edit");
	}

	@RequestMapping("/recoverEdit")
	public ModelAndView packageEdit(String depName,String packageName,String num,String [] data, HttpServletRequest request,
									   HttpServletResponse response)throws BusinessException{
		Map<String,Object> map = new HashMap<>();
		map.put("packageTiaoma",data[0]);
		List<ZsHuishouMingxi> zsHuishouMingxiList = zsHuishouMingxi.findAllHuishouMingxi(map);
		String huishouren = "";
		String jiaojieren = "";
		String huishouLiushui = "";
		if(zsHuishouMingxiList!=null&&zsHuishouMingxiList.size()!=0){
			ZsHuishouMingxi zsHuishouMingxi = zsHuishouMingxiList.get(0);
			huishouLiushui  = zsHuishouMingxi.getHuishouLiushui();
			ZsHuishou zsHuishou1 = zsHuishou.selectByPrimaryKey(huishouLiushui);
			huishouren = zsHuishou1.getHuishouHuishourenTiaoma();
			jiaojieren = zsHuishou1.getHuishouJiaojierenTiaoma();
		}
		request.setAttribute("huishouLiushui",huishouLiushui);
		request.setAttribute("huishouren",huishouren);
		request.setAttribute("jiaojieren",jiaojieren);
		request.setAttribute("depName",depName);
		request.setAttribute("packageName",packageName);
		request.setAttribute("num",num);
		List<String> list = new ArrayList<>();
		for (int i = 0; i < data.length; i++) {
			list.add(data[i]);
		}

		request.setAttribute("data",JSON.toJSON(list));
		return new ModelAndView("/huishou/huishou_edit");
	}
	
	@RequestMapping("/recoverSave.do")
	@ResponseBody
	public Map packageingSave(ZsHuishou huishou,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		
		Map<Object, Object> rtnMap = new HashMap<>();
		try {

			if(huishou.getHuishouLiushui() != null&&huishou.getHuishouLiushui()!=""){
				zsHuishou.updateByPrimaryKey(huishou);
				
			}else{
				rtnMap.put("status", false);
				rtnMap.put("msg", "编辑失败");
				
			}
			rtnMap.put("status", true);
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", false);
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}

	@RequestMapping("/recoverDel")
	@ResponseBody
	public Map<String,Object> recoverDel(){
		String packageList = request.getParameter("packageList");
		JSONArray jsonArrays = JSONObject.parseArray(packageList);
		List <String> packageArr = jsonArrays.toJavaList(String.class);
		Map<String,Object> rtnMap = new HashMap<>();
		try{
			if(packageArr.size()!=0){
				zsHuishouMingxi.deleteByTiaoma(packageArr);
				zsWlPKService.deleteByPackageTiaomaArr(packageArr);
				zsPKIMService.deleteByPackageTiaomaArr(packageArr);
				rtnMap.put("msg","删除成功");
				rtnMap.put("status",true);
			}else {
				rtnMap.put("msg","请选择数据");
				rtnMap.put("status",false);
			}

		}catch (Exception e){
			e.printStackTrace();
			rtnMap.put("msg","删除失败");
			rtnMap.put("status",false);
		}

		return rtnMap;
	}
	
	@RequestMapping("/recoverDel.do")
	@ResponseBody
	public Map packageingDel(HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<>();
		try {
			String ids = request.getParameter("id");
			String[] arraId = ids.split(",");
			Map<String,Object> map = new HashMap<>();
			for(String tid : arraId){
				map.put("huishouLiushui", tid);
				List<ZsHuishouMingxi> zsHsMxlist =  zsHuishouMingxi.findAllHuishouMingxi(map,0);
				List<String> list = new ArrayList<>();
				List <ZsWanglan> wlList = new ArrayList<>();
				//取出所有的packId
				for(ZsHuishouMingxi zsHuishoumingxi:zsHsMxlist){
					list.add(zsHuishoumingxi.getHuishouWupinbaoTiaoma());
				}
				//取出网篮的条码 变更网篮的状态
				map.put("packTmArr", list);
				if(!list.isEmpty()){
					List<ZsWanglanpackage> zsWlPacklist =zsWlPKService.findAllWlpackListNoPage(map);
					ZsWanglan zsWanglan= null;
					for(ZsWanglanpackage zsWLpack:zsWlPacklist){
						zsWanglan = new ZsWanglan();
						zsWanglan.setWlTiaoma(zsWLpack.getWanglanTiaoma());
						zsWanglan.setWlState(0);
						wlList.add(zsWanglan);
					}
					//改变wanglan表的网篮状态
					zsWlService.updateBatch(wlList);
				}
				//删除wanglanpack表的内容
				if(!list.isEmpty()){
					zsWlPKService.deleteBatch(list);
				}
				
				//删除大表的内容
				if(!list.isEmpty()){
					zsPKIMService.deleteBatch(list);
				}
				zsHuishou.deleteByPrimaryKey(tid);
				zsHuishouMingxi.deleteByhsls(tid);
				
				
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "删除成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "删除失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	/**点击回收批次查询明细内容 */
	@RequestMapping("/recoverMingxiList.do")
	@ResponseBody
	public Map recoverMingxiList(String id,HttpServletRequest request,HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<>();
		try {
			Map<String,Object> map =new HashMap<>();
			if(StringUtils.isNotBlank(id)){
				map.put("huishouLiushui", id);
			}
			List<ZsHuishouMingxi> mingxiList = zsHuishouMingxi.findAllHuishouMingxi(map,0);
			rtnMap.put("mxList", mingxiList);
			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	
	
	@RequestMapping("/recAndroid")
	@ResponseBody
	public Map recoverAndroid(String pdata)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap< >();
		System.out.print(pdata);
		JSONObject json = JSON.parseObject(pdata);
		String empId = json.getString("accetManCode");
		String huishouren = json.getString("manCode");
//		String wlBarcode = json.getJSONArray("basketBarcodeArr");
		String wlBarcode = json.getString("MeshBasketCode");
		JSONArray packageBarcodeArr = json.getJSONArray("packageBarcodeArr");
		try {
			List<ZsPackageImformation> list  = new ArrayList<>();
			for(int m =0;m<packageBarcodeArr.size();m++){
				Object jsonObject1 = packageBarcodeArr.get(m);
				JSONObject jsonObject = JSONObject.parseObject(jsonObject1.toString());
				if(jsonObject!=null){
					String packageBarcode = jsonObject.getString("packageTiaoma");
					ZsPackageImformation zsPackageImformation = new ZsPackageImformation();
					zsPackageImformation  =  zsPKIMService.selectByPrimaryKey(packageBarcode);
					list.add(zsPackageImformation);
				}
			}
			int success = tbWutiaoma.huishouAndroid(list,wlBarcode, empId,huishouren);
			if(success==1){
				rtnMap.put("status", "true");
				rtnMap.put("msg", "提交成功");
			}else if(success==0){
				rtnMap.put("status", "false");
				rtnMap.put("msg", "提交失败");
			}
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "提交失败");
			e.printStackTrace();
		}
		return rtnMap;
		
	}
	
	
	public Map<Object, Object> savePack(ZsHuishou zsHuishou ,HttpServletRequest request,
			HttpServletResponse response) throws BusinessException{
		String [] packageId = request.getParameterValues("packId");
		String [] hswlTiaoma = request.getParameterValues("packWl");
		String [] packageTm = request.getParameterValues("packTm");
		String [] packageName = request.getParameterValues("packName");
		String [] packageKeshi  = request.getParameterValues("packageKeshi");

		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			Map<Integer,List<TbProduct>> queshiMap = null;
			
			int success = tbWutiaoma.huishouTm(zsHuishou,packageTm,packageId,packageName,packageKeshi,hswlTiaoma,
					queshiMap);
			if(success==1){
				rtnMap.put("status", "true");
				rtnMap.put("msg", "回收成功");
			}else{
				rtnMap.put("status", "false");
				rtnMap.put("msg", "回收失败");
			}
			
//		 tbWutiaoma.packageAdd(zsHuishou, packageId, packageNum, packageName, qixiepackageId, productId, productName, productSize, productBarCode, productqueshiNum,queshiMap);
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "回收失败");
			e.printStackTrace();
		}
		return rtnMap;
	}

	
	@RequestMapping("/checkTiaoma.do")
	@ResponseBody
	public Map checkTiaoma(HttpServletRequest request,HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			String tiaoma = request.getParameter("tiaoma");
			
			if(tiaoma.startsWith("EMP")){
				//查员工
			}else if(tiaoma.startsWith("BAO")){
				//查询包
			}else if(tiaoma.startsWith("WL")){
				//查询网篮
			}else{
				
			}
			//TODO
			rtnMap.put("status", "false");
			rtnMap.put("msg", "网篮使用");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "查询失败");
			e.printStackTrace();
		}
		return rtnMap;
		
	}
	
	@RequestMapping("/huishouList.do")
	public ModelAndView huishouList(String searchTxt, String st, String et, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Integer pageNo = request.getParameter("pageIndex")==null? 1 :Integer.valueOf(request.getParameter("pageIndex"));
		Map<String,Object> map =new HashMap<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        Date startTime = null;
        Date endTime = null;
		if(StringUtils.isNotBlank(searchTxt)){
			map.put("searchTxt", searchTxt);
		}
		try {
			if (StringUtils.isNotBlank(st)) {
				startTime = sdf.parse(st);
				map.put("startTime",startTime);
			}
	        if (StringUtils.isNotBlank(et)) {
	        	endTime = sdf.parse(et);
	        	map.put("endTime", endTime);
			}
        }catch (ParseException e) {
			e.printStackTrace();
		}
		map.put("pageNo", pageNo);
		map.put("pageSize", Const.PAGE_SIZE);
		PageInfo<ZsHuishou> page = zsHuishou.findAllHuiShou(map);
		request.setAttribute("huishouList", page.getList());
		request.setAttribute("searchTxt", searchTxt==null?"":searchTxt);
		request.setAttribute("total", page.getPages());
		request.setAttribute("empmap", StartUpOnLoadData.emMap);
		return new ModelAndView("/wupinfafang/huishouchaxun/huishou_list");
	}

	/**
	 * 加载部门
	 *
	 * @return
	 */
	@RequestMapping("/addPackage")
	@ResponseBody
	public Map<String,Object> addPackageHtml() {
		Map<String, Object> map = new HashMap<>();
		List<TbDepartment> depList = tbDepartmentService.findAllDepartment();
		List<SendIm> sendImList = sendImservice.findAll(new HashMap<>());
		Collections.sort(depList,new TbDepartSort());
		Map<String,Object> rtnMap = new HashMap<>();
		rtnMap.put("depList",depList);
		rtnMap.put("status",true);
		rtnMap.put("sendImList",sendImList);
		return rtnMap;
	}

	@RequestMapping("/exportPackage")
	public void exportPackage(@RequestParam String data, HttpServletResponse response) throws Exception {
		List<ZsHuishou> list = JSON.parseArray(data, ZsHuishou.class);
		response.setContentType("application/octet-stream");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String name = "回收报表" + sdf.format(new Date()) + "-" + System.currentTimeMillis() + ".xlsx";
		response.setHeader(
				"content-disposition", "attachment;filename=" + new String(name.getBytes("UTF-8"), "iso-8859-1")
		);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ExcelUtils.getInstance().exportObjects2Excel(list, ZsHuishou.class, true, null, true, os);
		byte[] bytes = os.toByteArray();
		ServletOutputStream outputStream = response.getOutputStream();
		outputStream.write(bytes);
		outputStream.close();
	}

}
